<template>
  <div>
      <div style="display: flex; justify-content: center; align-items: center;">
        <el-form :inline="true" :model="formInline" label-width="100px">
          <el-form-item label="进货单号：">
            <el-input v-model="formInline.Number" placeholder="请输入" style="width: 150px;"></el-input>
          </el-form-item>
          <el-form-item label="单据状态">
            <el-select v-model="formInline.Status" placeholder="请选择" style="width: 150px;">
              <el-option label="待审核" value="待审核"></el-option>
              <el-option label="未入库" value="未入库"></el-option>
              <el-option label="部分入库" value="部分入库"></el-option>
              <el-option label="已入库" value="已入库"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="formInline.Supplier" placeholder="请选择" style="width: 150px;">
              <el-option
      v-for="item in tableData"
      :key="item.s_MIndex"
      :label="item.s_MSupplierName"
      :value="item.s_MIndex">
    </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="进货日期">
            <el-date-picker v-model="formInline.date" type="date" placeholder="选择日期" style="width: 120px;"></el-date-picker>
            至
            <el-date-picker v-model="formInline.date1" type="date" placeholder="选择日期" style="width: 120px;"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button  @click="chongzhi">重置</el-button>
          </el-form-item>
        </el-form>
      </div >
      
      <div style="display: flex;">
        <div style="width: 90px;">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <div style="width: 90px;">
          <el-button type="primary" @click="handleShen">审核</el-button>
        </div>
        <div style="width: 90px;">
          <el-button type="primary" @click="handleDel" >删除</el-button>
        </div>
      </div>
      <div style="overflow-x: auto;">
        <el-table :data="data" style="width: 100%" class="dataTable" @selection-change="handleSelectionChangeDel">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="p_OIndex" label="序号"></el-table-column>
          <el-table-column prop="p_OOrderNumber" label="进货单号"></el-table-column>
          <el-table-column prop="p_OStatus" label="单据状态" >
            <template slot-scope="scope">
              <span :style="{ color: getStatusColor(scope.row.p_OStatus) }">
                {{ scope.row.p_OStatus }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="进货日期">
            <template slot-scope='scope'>
              <span>{{ filterTime(scope.row.p_ODate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="p_OContactPerson" label="联系人"></el-table-column>
          <el-table-column prop="p_OContactInformation" label="联系方式"></el-table-column>
          <el-table-column prop="p_OQuantity" label="货品数量"></el-table-column>
          <el-table-column prop="p_OAmount" label="货品金额"></el-table-column>
          <el-table-column prop="p_OPurchased" label="进货货品"></el-table-column>
          <el-table-column prop="p_OCreator" label="制单人"></el-table-column>
          <el-table-column prop="p_ODepartment" label="所在部门"></el-table-column>
          <el-table-column label="制单时间">
            <template slot-scope='scope'>
              <span>{{ filterTime(scope.row.p_OCreationTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="p_OApprover" label="审核人"></el-table-column>
          <el-table-column label="审核时间">
            <template slot-scope='scope'>
              <span>{{ filterTime(scope.row.p_OApproverTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button 
                @click="JhUpd(scope.row)" 
                type="text"
                :disabled="scope.row.p_OStatus === '已入库'||scope.row.p_OStatus==='部分入库'||scope.row.p_OStatus==='未入库'" 
              >
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
          <el-pagination v-on:size-change="handleSizeChange"
          v-on:current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="rows">
</el-pagination>


<el-dialog
title="进货新增"
:visible.sync="ddxz"
:size="'auto'"
>
<h3>基础信息</h3>
<el-form ref="AddForm" :model="AddForm" :rules="rules" label-width="100px" >
<el-row>
  <el-col :span="12">
    <el-form-item label="进货单号">
      <el-input v-model="AddForm.jindex" placeholder="自动获取系统编号" style="width: 200px;" disabled readonly/>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="进货日期" prop="jdate">
      <el-date-picker style="width: 200px;"
        v-model="AddForm.jdate"
        type="date"
        format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="供应商" prop="Suname">
      <el-select v-model="AddForm.Suname" placeholder="请选择供应商" style="width: 200px;" @change="getSupplierInfo">
        <el-option
        v-for="item in tableData"
        :key="item.s_MIndex"
        :label="item.s_MSupplierName"
        :value="item.s_MIndex">
      </el-option>
      </el-select>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="联系人" prop="Sren">
      <el-input v-model="AddForm.Sren" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="联系方式" prop="Sphone">
      <el-input v-model="AddForm.Sphone" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="进货部门" prop="Sjpum">
      <el-cascader v-model="AddForm.Sjpum"
      :options="options"
      :props="{ checkStrictly:true }"
      v-on:change="handleCascaderChange">
    
    </el-cascader>
    </el-form-item>
    
  </el-col>
  <el-col :span="12">
    <el-form-item label="进货人" prop="Sjname">
      <el-select v-model="AddForm.Sjname" placeholder="请选择" style="width: 200px;" >
        <el-option
        v-for="item in tableData"
        :key="item.s_MIndex"
        :label="item.s_MPurchasingRepresentative"
        :value="item.s_MIndex">
      </el-option>
      </el-select>
    </el-form-item>
  </el-col>
  <el-col :span="24">
    <el-form-item label="备注" prop="Sjbez">
      <el-input v-model="AddForm.Sjbez" placeholder="请输入"/>
    </el-form-item>
  </el-col>
</el-row>
</el-form>
<h3>进货明细</h3>
<div style="width: 70px;">
  <!-- 添加按钮 -->
  <el-button type="primary" @click="MxAdd" style="font-size: 10px;">添加</el-button>
</div>


<div style="overflow-x: auto;">
  <el-table :data="jhmxdata" style="width: 100%" class="dataTable">
    <el-table-column prop="p_DSerialNumber" label="序号"  ></el-table-column>
    <el-table-column prop="p_DProductName" label="货品名称"></el-table-column>
    <el-table-column prop="p_DProductCode" label="货品编号"></el-table-column>
    <el-table-column prop="p_DSpecifications" label="规格型号"></el-table-column>
    <el-table-column prop="p_DUnit" label="单位"></el-table-column>
    <el-table-column prop="p_DProductType" label="货品类型"></el-table-column>
    <!-- <el-table-column prop="p_DQuantityReceived" label="当前库存"></el-table-column> -->
    <el-table-column label="货品数量">
      <template slot-scope="scope">
        <el-input v-model="scope.row.p_DQuantity" placeholder="请输入"></el-input>
      </template>
    </el-table-column>
    <el-table-column  label="进货单价">
      <template slot-scope="scope">
        <el-input v-model="scope.row.p_DUnitPrice" placeholder="请输入"></el-input>
      </template>
    </el-table-column>
    <el-table-column  label="金额">
      <template slot-scope="scope">
        {{ (scope.row.p_DQuantity || 0) * (scope.row.p_DUnitPrice || 0) }}
      </template>
    </el-table-column>
    <el-table-column  label="备注">
      <template slot-scope="scope">
        <el-input v-model="scope.row.p_DRemarks" placeholder="请输入"></el-input>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button @click="showDispose(scope.row)" type="text">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div>
  合计&nbsp;&nbsp;&nbsp;货品总数量：{{ totalQuantity }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;总金额：{{ totalAmount }}
  </div>
</div>
<h3>上传附件</h3>
<div>  
  <el-upload
  class="upload-demo"
  :action="getUploadUrl()"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-upload="beforeUpload"
  multiple
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过200MB</div>
</el-upload>

</div>  
<span slot="footer" class="dialog-footer">
  <el-button @click="ceanl">取消</el-button>
  <el-button @click="saveData">保存</el-button>
  
</span>
</el-dialog>

<el-dialog
title="添加货品"
:visible.sync="tjhp"
:size="'auto'"
>
<div style="overflow-x: auto;">
<el-table ref="tableName" :data="hpdata" style="width: 100%" class="dataTable" @selection-change="handleSelectionChange">
  <el-table-column type="selection" width="55"></el-table-column>
  <el-table-column prop="p_ProductId" label="序号"></el-table-column>
  <el-table-column prop="p_ProductName" label="货品名称"></el-table-column>
  <el-table-column prop="p_ProductCode" label="货品编号"></el-table-column>
  <el-table-column prop="p_ProductType" label="货品类型"></el-table-column>
  <el-table-column prop="p_SpecificationModel" label="规格型号"></el-table-column>
  <el-table-column prop="p_Unit" label="单位"></el-table-column>
  <el-table-column prop="p_InboundPrice" label="入库单价"></el-table-column>
  <!-- <el-table-column prop="p_CurrentStock" label="当前库存"></el-table-column> -->
</el-table>
<span slot="footer" class="dialog-footer">
  <el-button @click="tjhp = false">取消</el-button>
  <el-button @click="hpForm">确认</el-button>
</span>  
</div>
</el-dialog>


<el-dialog
title="进货修改"
:visible.sync="xgxz"
:size="'auto'"
>
<h3>基础信息</h3>
<el-form ref="UpdForm" :model="UpdForm" label-width="100px" >
<el-row>
  <el-col :span="12">
    <el-form-item label="编号">
      <el-input v-model="UpdForm.jindex1" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="进货日期">
      <el-date-picker style="width: 200px;"
        v-model="UpdForm.jdate1"
        type="date"
        format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
    </el-form-item>
  </el-col>
 
  <el-col :span="12">
    <el-form-item label="联系人">
      <el-input v-model="UpdForm.Sren1" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="联系方式">
      <el-input v-model="UpdForm.Sphone1" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
  </el-col>
  <el-col :span="24">
    <el-form-item label="备注">
      <el-input v-model="UpdForm.Sjbez1" placeholder="请输入"/>
    </el-form-item>
  </el-col>
</el-row>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="xgxz = false">取消</el-button>
    <el-button @click="xgsaveData">保存</el-button>
    
  </span>
</el-dialog>


<el-dialog
title="审核"
:visible.sync="shenhe"
:size="'auto'"
>

<el-form ref="ShenForm" :model="ShenForm" label-width="100px" >
<el-row>
  <el-col :span="12">
    <el-form-item label="编号" v-if="!isHidden">
      <el-input v-model="ShenForm.bh1" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="审核结果">
      <el-radio-group v-model="ShenForm.jieguo">
        <el-radio label="通过">通过</el-radio>
        <el-radio label="驳回">驳回</el-radio>
      </el-radio-group>
    </el-form-item>
  </el-col>
 
  <el-col :span="24">
    <el-form-item label="审核意见">
      <el-input v-model="ShenForm.yijian" placeholder="请输入"/>
    </el-form-item>
  </el-col>
</el-row>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="shenhe= false">取消</el-button>
    <el-button @click="ShenData">确认</el-button>
    
  </span>
</el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { MessageBox } from 'element-ui';
export default {
  data() {
    return {
      // tableData: [
      //   { p_OStatus: '已入库' },
      //   { p_OStatus: '未入库' },
      //   { p_OStatus: '待审核' },
      //   { p_OStatus: '部分入库' }
      // ],
      isHidden: true, // 控制文本框显示与隐藏的变量
        // 选中的序号数组
        selectedIds: [],
        selectedPOIndex:'',
      xlk:[],
      tableData: [ //供应商查询的下拉框
      ],
      value: "",
     options: [],//级联
      tjhp:false,
      ddxz:false,//新增的模态框
      xgxz:false,//修改的模态框
      shenhe:false,//审核的模态框
      data: [],
      jhmxdata:[],
      hpdata:[],
      fileList: [],
      currentPage: 1,
      pageSize: 10,
      rows: 0, // 数据总条数
      ShenForm:{
        bh1:'',
        jieguo:'',
        yijian:''
      },
      UpdForm:{
        jindex1:'',
        jdate1:'',
        Sphone1:'',
        Sren1:'',
        Sjbez1:''
      },
      AddForm:{
        jindex:'',
        jdate:'',
        Suname:'',
        Sren:'',
        Sphone:'',
        Sjpum:'',
        Sjname:'',
        Sjbez:''
      },
      formInline: {
          Number: '',
          Status: '',
          Supplier:'',
          date:'',
          date1:'',
      },
      rules: {
  Sphone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^[0-9]{11}$/, message: '联系方式必须为11位数字', trigger: 'blur' }
  ],
  jdate: [
    { required: true, message: '请输入日期', trigger: 'blur' },
  ],
  Suname: [
    { required: true, message: '请选择供应商', trigger: 'blur' },
  ],
  Sren: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
  ],
  Sjpum: [
    { required: true, message: '请选择部门', trigger: 'blur' },
  ],
  Sjname: [
    { required: true, message: '请选择进货人', trigger: 'blur' },
  ],

},
     // hpdata: [], // 表格数据
    selectedRows: [], // 选中的行数据
     // 定义状态对应的颜色映射关系
     orderNumber:'',
    }
  },
  methods: {
    getStatusColor(status) {
      const statusColorMap = {
        '已入库': 'green',
        '未入库': 'orange',
        '待审核': 'red',
        '部分入库':'blue'
      };
      return statusColorMap[status];
    },
    generateCode() {
      // 生成随机大写字母
      const randomLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));

      // 生成当前日期
      const currentDate = new Date().toISOString().slice(0, 10).replace(/-/g, '');

      // 生成4个随机数字
      const randomDigits = Math.floor(1000 + Math.random() * 9000);

      // 组合成编号
      return randomLetter + currentDate + randomDigits;
    },
    //进货审核
    ShenData(){
      axios.put(`http://localhost:5084/api/Purchaseorders/JhShen?to=${this.ShenForm.jieguo}`, {
        p_OIndex: this.ShenForm.bh1,
        p_Reviewcomments: this.ShenForm.yijian,
       
}).then(res => {
  if (res) {
    this.$message({
      message: '审核成功！',
      type: 'success'
    });

    this.shenhe = false;
    this.searchData(); // 重新填充销售机会列表
  }
})
.catch(err => {
  this.$message({
    message: '审核失败！',
    type: 'error'
  });
});

    },
    handleShen(){
        this.shenhe=true;
        this.ShenForm.bh1=this.selectedPOIndex;
       
    },
    //进货订单的修改
    JhUpd(row){
      this.xgxz=true;
      this.Yiji();
      this.UpdForm.jindex1=row.p_OIndex;
      this.UpdForm.jdate1=row.p_ODate;
      this.UpdForm.Sphone1=row.p_OContactInformation;
      this.UpdForm.Sren1=row.p_OContactPerson;
      this.UpdForm.Sjbez1=row.p_OReamr
    },//修改保存
    xgsaveData(){
      axios.put("http://localhost:5084/api/Purchaseorders/JhUpd", {
        p_OIndex: this.UpdForm.jindex1,
        p_ODate: this.UpdForm.jdate1,
        p_OContactPerson: this.UpdForm.Sren1,
        p_OContactInformation:this.UpdForm.Sphone1,
        p_OReamr:this.UpdForm.Sjbez1
}).then(res => {
  if (res) {
    this.$message({
      message: '修改成功！',
      type: 'success'
    });

    this.xgxz = false;
    this.searchData(); // 重新填充销售机会列表
  }
})
.catch(err => {
  this.$message({
    message: '修改失败！',
    type: 'error'
  });
});
    },
       // 处理复选框选中事件
       handleSelectionChangeDel(selection) {
this.selectedIds = selection.map(item => item.p_OIndex);
if (selection && selection.length > 0) {
      const selectedRow = selection[0]; // 获取选中的第一行数据
      this.selectedPOIndex = selectedRow.p_OIndex; // 获取选中行的编号
    } else {
      this.selectedPOIndex = ''; // 如果没有选中行，则清空选中行的编号
    }
    this.selectedRows = selection;//无法删除已审核的数据
     console.log(this.selectedIds);
     console.log( this.selectedPOIndex);
     
},//批量删除
  handleDel() {
    const hasUnstoredData = this.selectedRows.some(row => row.p_OStatus === '未入库' || row.p_OStatus === '部分入库' || row.p_OStatus === '已入库');
  if (!hasUnstoredData) {
    MessageBox.confirm('存在未入库的数据，确定删除所选单据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 执行删除操作的逻辑
      axios.delete('http://localhost:5084/api/Purchaseorders/JhDel', {
        data: this.selectedIds
      })
      .then(response => {
        this.$message({
          message: '删除成功！',
          type: 'success'
        });
        this.Qu();
        this.searchData();
      })
      .catch(error => {
        this.$message({
          message: '删除失败！',
          type: 'error'
        });
      });
    }).catch(() => {
      // 用户点击取消按钮时执行的操作，这里不需要执行任何操作
    });
  } else {
    this.$message.warning('无法删除已审核的数据');
  }
  },
    handleCascaderChange(value) {
      // 获取选中的 value 和 label
  const selectedValue = value[value.length - 1];
  const selectedLabel = this.getLabelByValue(selectedValue);
  this.AddForm.Sjpum = selectedValue.toString();
  // 打印选中的 value 和 label
  console.log('选中的 label 的值:', selectedLabel);
  console.log('选中的 value 的值:', selectedValue);
},
getLabelByValue(value) {
  // 在 options 中查找对应 value 的 label
  const findLabel = (options, value) => {
    for (const item of options) {
      if (item.value === value) {
        return item.label;
      }
      if (item.children) {
        const label = findLabel(item.children, value);
        if (label) {
          return label;
        }
      }
    }
    return null;
  };
  
  return findLabel(this.options, value);
  },
//一级下拉
Yiji() {
      axios.get("http://localhost:5084/api/OrganizationalStructure/GetYI")
        .then((response) => {
          this.options = response.data.map(item => {
            return {
              value: item.value,
              label: item.label,
              children: item.children
            };
          });
          console.log('获取到的数据:', this.options); // 打印获取到的数据
        })
        .catch((error) => {
          console.log(error);
        });
},//组织机构级联
    getSupplierInfo() {
      axios.get('http://localhost:5084/api/Suppliermanagement/QuName/QuName', {
    params: {
      Name:this.AddForm.Suname
    }
  }).then((response) => {
    this.AddForm.Sren = response.data.s_MContactPerson;
        this.AddForm.Sphone = response.data.s_MContactNumber;
        console.log(this.AddForm.Sren);
        console.log(this.AddForm.Sphone);
  }).catch((error) => {
    console.log(error);
  });
  },
    //查询供应商表作为下拉框
    Gys(){
      axios.get('http://localhost:5084/api/Suppliermanagement/Qu',{              
          }).then((response)=>{
             this.tableData=response.data;
            
          }).catch((error)=>{
             console.log(error);
            
          })
    },
    beforeUpload(file) {
    const isImage = file.type.includes('image');
    if (!isImage) {
      this.$message.error('只能上传图片文件');
    }
    const isLt200M = file.size / 1024 / 1024 < 200;
    if (!isLt200M) {
      this.$message.error('上传文件大小不能超过200MB');
    }
    return isImage && isLt200M;
  },
  
   // 获取动态的上传URL
   getUploadUrl() {
    // 构建上传URL，并将this.AddForm.jindex的值添加到URL中
    return `http://localhost:5084/api/PublicAttachment/Upload?num=${this.generateCode()}`;
  },
  handlePreview(file) {
const reader = new FileReader();
reader.onload = (e) => {
  const imageUrl = e.target.result;
  // 在这里可以使用 imageUrl 来显示预览图片
  // 例如，将 imageUrl 设置为 img 标签的 src 属性
  // 或者在模态框中显示预览图片
  console.log('预览图片:', imageUrl);
};
reader.readAsDataURL(file.raw);
},
handleRemove(file) {
const index = this.fileList.indexOf(file);
if (index !== -1) {
  this.fileList.splice(index, 1);
  // 在这里可以向服务器发送请求，删除对应的文件
  console.log('删除文件:', file.name);
}
},

    
    filterTime(date) {
if (date) {
  return date.split('T')[0];
} else {
  return '';
}
},
    handleTotalRecords(){
      if (this.totalRecords === 1) {  
      this.totalPages = 2; 
    } else {  
      this.totalPages = (this.pageSize * this.currentPage) + (this.totalRecords % this.pageSize === 0 ? 0 : this.totalRecords % this.pageSize) - 1;  
    }  
    // 根据需要执行其他逻辑  
  
    },
    //重置
    chongzhi(){
      this.formInline.Number='';
      this.formInline.Status='';
      this.formInline.Supplier='';
      this.formInline.date='';
      this.formInline.date1='';
    },
    searchData() {
        // 查询数据逻辑
  const { Number, Status, Supplier, date,date1 } = this.formInline;
  axios.get('http://localhost:5084/api/Purchaseorders/Fye', {
    params: {
      pageSize: this.pageSize,
      currentPage: this.currentPage,
      Number: Number,
      Status: Status,
      Supplier: Supplier,
      date: date,
      date1:date1
    }
  }).then((response) => {
    this.data = response.data;
   
    this.handleTotalRecords();
  }).catch((error) => {
    console.log(error);
  });
      // 查询逻辑
    },
    //货品信息查询全部
    HoupQu(){
      axios.get('http://localhost:5084/api/Productinformation/Qu',{              
          }).then((response)=>{
             this.hpdata=response.data;
          }).catch((error)=>{
             console.log(error);
            
          })
    },
    //进货明细查询的全部
    HpQU(){
          axios.get('http://localhost:5084/api/Purchasedetails/Qu',{              
          }).then((response)=>{
             this.jhdata=response.data;
          }).catch((error)=>{
             console.log(error);
             console.log(this.jhdata);
          })
    },
    //选中确认添加
    hpForm() {
const selectedRows = this.$refs.tableName.selection; // 获取所有选中的行数据
  // 检查是否至少选择了一行
  if (selectedRows.length > 0) {
    // 遍历选中的每一行数据
    selectedRows.forEach(row => {
      // 将选中行数据添加到显示数据数组中
      this.jhmxdata.push({
        p_DSerialNumber: this.jhmxdata.length + 1, // 序号为当前数组长度加1
        p_DProductName: row.p_ProductName,
        p_DProductCode: row.p_ProductCode,
        p_DSpecifications: row.p_SpecificationModel,
        p_DUnit: row.p_Unit,
        p_DProductType:row.p_ProductType,
        p_DQuantity:null,
        p_DUnitPrice: row.p_InboundPrice,
        p_DQuantityReceived:row.p_CurrentStock,
        p_DRemarks:null,
      });
    });
    
    // 关闭弹窗
    this.tjhp = false;
  } else {
    // 提示用户至少选择一行数据
    this.$message.warning('请至少选择一行数据！');
  }
},
   //进货明细移除
   showDispose(row){
    if (confirm("确定删除吗")) {
    axios.delete(`http://localhost:5084/api/Purchasedetails/Del?id=${row.p_DSerialNumber}`)
    .then(response => {
      this.$message({
                message: '删除成功！',
                type: 'success'
              });
              this.HpQU();
    })
    .catch(error => {
      this.$message({
                message: '删除失败！',
                type: 'success'
              });
    });
}
   },
    //进货明细新增
    MxAdd(){
         this.tjhp=true;
         this.HoupQu();
    },
     // 处理复选框选中状态改变事件
  handleSelectionChange(selection) {
    this.selectedRows = selection;
  },
    //进货订单新增
    handleAdd(){
      this.ddxz=true;
      this.Gys();
    
       this.Yiji();
        
    },
    ceanl(){//取消
      this.jhmxdata = []; // 清空显示数据数组
      this.AddForm.jdate='';
      this.AddForm.Suname='';
      this.AddForm.Sren='';
      this.AddForm.Sphone='';
      this.AddForm.Sjpum='';
      this.AddForm.Sjname='';
      this.AddForm.Sjbez='';

      this.ddxz=false;
    },
    saveData() {//保存
      this.$refs.AddForm.validate((valid) => {
    if (valid) {
      // 保存操作
      this.saveForm();
      // 明细
      this.Jhmx();
      this.ddxz = false;        
      this.jhmxdata = []; // 清空显示数据数组
      this.AddForm.jdate='';
      this.AddForm.Suname='';
      this.AddForm.Sren='';
      this.AddForm.Sphone='';
      this.AddForm.Sjpum='';
      this.AddForm.Sjname='';
      this.AddForm.Sjbez='';
      
    } else {
      // 表单验证失败，可以在这里进行相应的提示或处理
    }
  });
},
// 生成编号
//const orderNumber = this.generateCode();
   // 进货订单保存
saveForm() {

 // 获取当前日期
 const currentDate = new Date();

// 将日期格式化为 'yyyy-MM-dd' 形式
const formattedDate = currentDate.toISOString().slice(0, 10); // 获取 'yyyy-MM-dd' 部分
const gys=this.AddForm.Suname.toString();
const jhr=this.AddForm.Sjname.toString();
 // 生成编号
 this.orderNumber = this.generateCode();
axios.post("http://localhost:5084/api/Purchaseorders/JhAdd", {
    p_OOrderNumber: this.orderNumber,
    p_OStatus: '待审核',
    p_ODate: this.AddForm.jdate,
    p_OSupplier: gys,
    p_OContactPerson: this.AddForm.Sren,
    p_OContactInformation: this.AddForm.Sphone,
    p_OPurchasingDepartment:this.AddForm.Sjpum,
    p_OPurchaser: jhr,
    p_OQuantity: this.totalQuantity,
    p_OAmount: this.totalAmount,
    p_OPurchased: this.concatenatedProductNames,
    p_OCreator: 'admin',
    p_ODepartment: '采购部',
    p_OCreationTime: formattedDate, // 使用正确的日期变量
    p_OApprover: null, 
    p_OApproverTime: null, 
    p_Reviewcomments: null,
    p_OReamr:this.AddForm.Sjbez
  })
  .then(res => {
    if (res.data) { // 注意这里应该判断 res.data 而不是 res
      this.$message({
        message: '添加成功！',
        type: 'success'
      });
      this.searchData();
      this.Qu();
    } else {
      this.$message({
        message: '添加失败！',
        type: 'error' // 应该是 error 类型
      });
    }
  })
  .catch(error => {
    console.error('请求失败:', error);
    this.$message.error('请求失败，请稍后重试！');
  });
},

Jhmx(){//j进货明细
  
      const promises = this.jhmxdata.map(row => {
const postData = {
  p_DProductName: row.p_DProductName,
  p_DProductCode: row.p_DProductCode,
  p_DSpecifications: row.p_DSpecifications,
  p_USpecifications: row.p_USpecifications,
  p_DUnit: row.p_DUnit,
  p_DProductType: row.p_DProductType,
  p_DQuantity: row.p_DQuantity,//进货数量
  p_DUnitPrice: row.p_DUnitPrice,
  p_DAmount:  (row.p_DQuantity || 0) * (row.p_DUnitPrice || 0) ,
  //p_DQuantityReceived: row.p_DQuantityReceived,//当前库存
  p_DRemarks: row.p_DRemarks,
  p_DPurchasCode:this.orderNumber,
};

return axios.post("http://localhost:5084/api/Purchasedetails/Add", postData)
  .then(res => {
    return res;
  })
  .catch(error => {
    console.error('添加失败:', error);
    throw new Error('添加失败');
  });
});

Promise.all(promises)
.then(results => {
  const isSuccess = results.every(res => res);
  if (isSuccess) {
    this.$message({
      message: '添加成功！',
      type: 'success'
    });
  } else {
    this.$message({
      message: '添加失败！',
      type: 'error'
    });
  }
})
.catch(() => {
  this.$message.error('添加失败，请稍后重试！');
});
    },
    
    
     Qu(){
      axios.get('http://localhost:5084/api/Purchaseorders/Qu', {
  }).then((response) => {
    this.rows = response.data.length;
    this.xlk=response.data;
  }).catch((error) => {
    console.log(error);
  });
     },
    // 处理页码变化
    handleSizeChange: function (size) {
  this.pageSize = size;
  this.searchData();
  },
    handleCurrentChange: function (page) {
  this.currentPage = page;
  this.searchData();
},
  },
  mounted: function () {
   //this.currentPage = 1;
 
   this.searchData();
 
  this.Qu();
  this.Gys();
},computed: {
uniqueSupplierNames() {
  // 提取并去重 p_OSupplier 字段
  const uniqueSet = new Set();
  this.xlk.forEach(item => {
    uniqueSet.add(item.p_OSupplier);
  });
  return Array.from(uniqueSet);
},//供应商下拉框去重
  totalQuantity() {
    // 计算货品数量的总和
    return this.jhmxdata.reduce((total, item) => total + (parseFloat(item.p_DQuantity) || 0), 0);
    
  },
  concatenatedProductNames() {
    return this.jhmxdata
      .map(item => `${item.p_DProductName}`) // 将每个货品名称转换为所需格式
      .join('，'); // 使用逗号拼接所有转换后的货品名称
  },
  totalAmount() {
    // 计算金额的总和
    return this.jhmxdata.reduce((total, item) => total + ((item.p_DQuantity || 0) * (item.p_DUnitPrice || 0)), 0);
  },
},
}

</script>


<style scoped>  
/* 使用深度选择器来覆盖Element UI的默认样式 */  
::v-deep .dataTable .el-table__header-wrapper th {  
background-color: #F5F5F5; /* 设置标题单元格的背景颜色为蓝色 */  
color: black; /* 如果需要的话，设置标题单元格的文字颜色为白色 */  
}  

</style>